<template>
  <view>
    <view class="upload-wrap">
      <view class="btn-click mgb-16 upload-btn" @click="handleUploadClick" v-show="!disabled">
        <image :src="icons.upload" mode="aspectFill" class="upload-icon" />
        <text class="upload-text">上传{{ title[type] }}</text>
      </view>
      <view class="mgb-16 file-wrap" v-for="(item, index) in fileList" :key="index">
        <view class="btn-click file-line" @click="handlePreview(item)">
          <view class="file-info">
            <image :src="icons.file" mode="aspectFill" class="file-icon" />
            <text class="file-name">{{ item.name || title[type] }}</text>
          </view>
          <image :src="icons.close" mode="aspectFill" class="file-icon" v-if="!disabled"
            @click.stop="handleDeleteFile(index)" />
        </view>
      </view>
      <view class="mgb-16 file-wrap" v-if="fileList.length === 0 && disabled">
        <view class="file-line">
          <text class="file-empty">暂无数据</text>
        </view>
      </view>
    </view>
    <xe-upload ref="XeUpload" :options="uploadOptions" @callback="handleUploadCallback"></xe-upload>
  </view>
</template>

<script>
export default {
  name: 'UploadDemo',
  props: {
    type: {
      default: 'file', // 仅保留文件类型
      type: String,
    },
    list: {
      default: () => ([]),
      type: Array,
    },
    disabled: {
      default: false,
      type: Boolean,
    },
  },
  data() {
    return {
      uploadOptions: {
        // url: 'http://your-upload-api.com/upload', // 上传地址
      },
      fileList: [],
      title: {
        file: '文件',
      },
      icons: {
        upload: '/static/icon_upload.png',
        close: '/static/icon_close.png',
        file: '/static/icon_file.png',
      },
    };
  },
  watch: {
    list: {
      handler(val) {
        this.fileList = val || [];
      },
      immediate: true,
      deep: true,
    },
  },
  methods: {
    handleUploadClick() {
      // 上传文件
      this.$refs.XeUpload.upload(this.type);
    },
     handleUploadCallback(e) {
        console.log('UploadCallback Data:', e); // 打印上传回调数据
    
        if (['choose', 'success'].includes(e.type)) {
          const tmpFiles = (e.data || []).map((item) => {
            console.log('Processing File Item:', item); // 打印每个文件对象
    
            // 使用可选链操作符和空值合并操作符
            const response = item.response?.result ?? {};
            const tmpUrl = response.filePath ?? item.tempFilePath;
            const tmpName = response.fileName ?? item.name;
    
            // 触发事件通知父组件
            this.$emit('success', { tempFilePath: tmpUrl, name: tmpName });
    
            return {
              id: Date.now().toString(), // 唯一 ID
              url: tmpUrl,
              name: tmpName,
              fileType: 'file',
            };
          });
          this.fileList.push(...tmpFiles);
        }
      },
    handlePreview({ url }) {
      console.log('PreviewFile URL:', url);

      // #ifndef H5
      uni.openDocument({
        filePath: url,
        fail: (err) => {
          console.log('openDocument Fail:', err);
          uni.showToast({ icon: 'none', title: '文件预览失败' });
        },
      });
      // #endif

      // #ifdef H5
      if (url) {
        window.open(url, '_blank');
      } else {
        uni.showToast({ icon: 'none', title: '无效文件链接' });
      }
      // #endif
    },
    handleDeleteFile(index) {
      this.fileList.splice(index, 1);
    },
  },
};
</script>

<style lang="scss" scoped>
view {
  box-sizing: border-box;
}

.btn-click {
  transition: all 0.3s;
  opacity: 1;
}

.btn-click:active {
  opacity: 0.5;
}

.mgb-16 {
  margin-bottom: 16rpx;

  &:last-child {
    margin-bottom: 0;
  }
}

.upload-wrap {
  width: 100%;
  border-radius: 16rpx;
  background: white;
  padding: 32rpx;

  .upload-btn {
    width: 100%;
    height: 176rpx;
    border: 2rpx dashed #AAAAAA;
    background: #FAFAFA;
    border-radius: 16rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;

    .upload-icon {
      width: 48rpx;
      height: 48rpx;
      margin-bottom: 8rpx;
    }

    .upload-text {
      font-size: 26rpx;
      color: #9E9E9E;
      line-height: 40rpx;
    }
  }

  .file-wrap {
    .file-line {
      width: 100%;
      background: #F5F5F5;
      border-radius: 8rpx;
      padding: 16rpx;
      font-size: 26rpx;
      color: #1A1A1A;
      line-height: 40rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .file-info {
        width: 90%;
        display: flex;
        align-items: center;

        .file-name {
          max-width: 80%;
          padding-left: 16rpx;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }

      .file-icon {
        width: 40rpx;
        height: 40rpx;
        flex-shrink: 0;
      }

      .file-empty {
        color: #999999;
      }
    }
  }
}
</style>